<template>
  <div class="user-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button icon="el-icon-back" @click="goBack" plain>返回</el-button>
        <h2>用户管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="refreshUsers" plain>
          <i class="el-icon-refresh"></i>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalUsers }}</div>
              <div class="stats-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon active">
              <i class="el-icon-check"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ activeUsers }}</div>
              <div class="stats-label">活跃用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon new">
              <i class="el-icon-plus"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ newUsers }}</div>
              <div class="stats-label">新增用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索用户昵称/学号/手机号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" plain>搜索</el-button>
          <el-button @click="resetSearch" plain>重置</el-button>
          <el-button type="success" @click="handleAdd" plain>添加用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="paginatedUserList"
        border
        style="width: 100%"
      >
        <el-table-column prop="userId" label="ID" width="220"></el-table-column>
        <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
        <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
        <el-table-column label="头像" width="100">
          <template slot-scope="scope">
            <el-avatar :size="40" :src="scope.row.avatar || defaultAvatars[0]" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              plain
            >编辑</el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              plain
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="头像">
          <div class="avatar-selector">
            <div 
              v-for="(avatar, index) in defaultAvatars" 
              :key="index"
              class="avatar-option"
              :class="{ 'selected': form.avatar === avatar }"
              @click="selectAvatar(avatar)"
            >
              <el-avatar 
                :size="60" 
                :src="avatar"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="handleSubmit" plain>确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import userService from '@/services/user.service'

export default {
  name: 'UserList',
  data() {
    return {
      loading: false,
      userList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogType: 'add',
      currentId: null,
      searchForm: {
        keyword: ''
      },
      form: {
        studentId: '',
        nickname: '',
        phone: '',
        password: '',
        avatar: ''
      },
      rules: {
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { pattern: /^\d{8,12}$/, message: '学号格式不正确', trigger: 'blur' },
          { validator: this.validateStudentId, trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
          { validator: this.validateNickname, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
          { validator: this.validatePhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      },
      defaultAvatars: [
        require('@/assets/avatars/avatar1.png'),
        require('@/assets/avatars/avatar2.png'),
        require('@/assets/avatars/avatar3.png'),
        require('@/assets/avatars/avatar4.png')
      ]
    }
  },
  computed: {
    // 过滤后的用户列表
    filteredUserList() {
      if (!Array.isArray(this.userList)) {
        console.warn('userList不是数组:', this.userList)
        return []
      }
      
      if (!this.searchForm.keyword) {
        return this.userList
      }
      const keyword = this.searchForm.keyword.toLowerCase()
      return this.userList.filter(user => 
        user.studentId?.toLowerCase().includes(keyword) ||
        user.nickname?.toLowerCase().includes(keyword) ||
        user.phone?.includes(keyword)
      )
    },
    // 分页后的用户列表
    paginatedUserList() {
      if (!Array.isArray(this.filteredUserList)) {
        console.warn('filteredUserList不是数组:', this.filteredUserList)
        return []
      }
      
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredUserList.slice(start, end)
    },

    // 总用户数
    totalUsers() {
      return this.userList.length
    },

    // 活跃用户数（这里简单统计有头像的用户）
    activeUsers() {
      return this.userList.filter(user => user.avatar).length
    },

    // 新增用户数（这里简单统计最近7天注册的用户）
    newUsers() {
      const sevenDaysAgo = new Date()
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
      return this.userList.filter(user => {
        if (!user.createTime) return false
        const createDate = new Date(user.createTime)
        return createDate >= sevenDaysAgo
      }).length
    }
  },
  mounted() {
    console.log('UserList component mounted')
    this.fetchUsers()
  },
  methods: {
    // 获取token的函数
    getToken() {
      return localStorage.getItem('token') || ''
    },

    // 验证学号是否已存在
    async validateStudentId(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (this.dialogType === 'edit') {
        callback()
        return
      }
      try {
        const response = await userService.checkStudentId(value)
        if (response && response.code === 200 && response.data) {
          callback(new Error('该学号已被注册'))
        } else {
          callback()
        }
      } catch (error) {
        callback()
      }
    },

    // 验证昵称是否已存在
    async validateNickname(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (this.dialogType === 'edit') {
        callback()
        return
      }
      try {
        const response = await userService.checkNickname(value)
        if (response && response.code === 200 && response.data) {
          callback(new Error('该昵称已被使用'))
        } else {
          callback()
        }
      } catch (error) {
        callback()
      }
    },

    // 验证手机号是否已存在
    async validatePhone(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (this.dialogType === 'edit') {
        callback()
        return
      }
      try {
        const response = await userService.checkPhone(value)
        if (response && response.code === 200 && response.data) {
          callback(new Error('该手机号已被注册'))
        } else {
          callback()
        }
      } catch (error) {
        callback()
      }
    },

    // 更新总数
    updateTotal() {
      this.total = this.filteredUserList.length
    },

    // 获取用户列表
    async fetchUsers() {
      console.log('开始获取用户列表')
      this.loading = true
      try {
        console.log('调用 userService.getUsers()')
        const response = await userService.getUsers()
        console.log('API响应:', response)
        console.log('响应类型:', typeof response)
        console.log('响应是否为对象:', response && typeof response === 'object')
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'users', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          // 确保每个用户都有头像，并且头像URL是完整的
          this.userList = (data || []).map(user => {
            let avatarToUse = this.defaultAvatars[0]; // 默认回退到第一个本地头像

            if (user.avatar && typeof user.avatar === 'string' && user.avatar !== '') {
              // 只要user.avatar是一个非空字符串，就尝试使用它
              // 因为Webpack处理的本地路径不会以http开头，但仍然是有效的src
              avatarToUse = user.avatar;
            } else {
              // 如果user.avatar是null, undefined, 或空字符串，则回退到本地默认头像
              console.warn('检测到无效或空头像URL，回退到本地默认头像:', user.avatar);
              avatarToUse = this.defaultAvatars[0]; // 明确使用第一个本地默认头像
            }
            
            return {
              ...user,
              avatar: avatarToUse
            };
          })
          console.log('处理后的用户列表:', this.userList)
          console.log('用户列表长度:', this.userList.length)
          this.updateTotal()
        } else {
          console.error('API返回错误:', response)
          console.error('响应code:', response?.code)
          console.error('响应message:', response?.message)
          this.userList = [] // 确保设置为空数组
          this.updateTotal()
          Message.error(response?.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        console.error('错误类型:', typeof error)
        console.error('错误名称:', error.name)
        console.error('错误消息:', error.message)
        console.error('错误堆栈:', error.stack)
        if (error.response) {
          console.error('响应状态:', error.response.status)
          console.error('响应数据:', error.response.data)
        }
        this.userList = [] // 确保设置为空数组
        this.updateTotal()
        Message.error(error?.response?.data?.message || error?.message || '获取用户列表失败')
      } finally {
        console.log('设置loading为false')
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.updateTotal()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.keyword = ''
      this.currentPage = 1
      this.updateTotal()
    },

    // 选择头像
    selectAvatar(avatar) {
      this.form.avatar = avatar
    },

    // 添加用户
    handleAdd() {
      this.dialogType = 'add'
      this.currentId = null
      // 清空表单
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      // 设置默认头像
      this.form.avatar = this.defaultAvatars[0]
      this.dialogVisible = true
    },

    // 编辑用户
    handleEdit(row) {
      this.dialogType = 'edit'
      this.currentId = row.userId
      // 清空表单
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      // 设置表单数据
      this.form.studentId = row.studentId
      this.form.nickname = row.nickname
      this.form.phone = row.phone
      this.form.avatar = row.avatar || this.defaultAvatars[0] // 如果没有头像，使用默认头像
      // 编辑模式下不显示密码字段
      this.form.password = ''
      this.dialogVisible = true
    },

    // 删除用户
    handleDelete(row) {
      MessageBox.confirm(
        `确定要删除用户 "${row.nickname}" 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await userService.deleteUser(row.userId)
          if (response && response.code === 200) {
            Message.success('删除成功')
            this.fetchUsers()
          } else {
            Message.error(response?.message || '删除失败')
          }
        } catch (error) {
          console.error('删除用户失败:', error)
          Message.error(error?.response?.data?.message || error?.message || '删除用户失败')
        }
      }).catch((error) => {
        // 用户取消操作，不需要处理
        if (error !== 'cancel') {
          console.error('删除用户操作失败:', error)
        }
      })
    },

    // 提交表单
    async handleSubmit() {
      if (!this.$refs.formRef) return
      
      await this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            let response
            if (this.dialogType === 'add') {
              // 创建用户时使用register API，确保包含所有必需字段
              const userData = {
                studentId: this.form.studentId.trim(),
                nickname: this.form.nickname.trim(),
                password: this.form.password,
                phone: this.form.phone.trim(),
                avatar: this.form.avatar // 直接发送用户选择的完整头像URL，因为现在URL是短的，可以完整存储
              }
              
              // 验证所有必需字段
              if (!userData.studentId || !userData.nickname || !userData.password || !userData.phone) {
                Message.error('请填写所有必需字段')
                return
              }

              // 验证字段长度 (这些验证仍然需要，因为用户可以手动输入)
              if (userData.nickname.length > 50) {
                Message.error('昵称长度不能超过50个字符')
                return
              }
              if (userData.phone.length > 15) {
                Message.error('手机号长度不能超过15个字符')
                return
              }
              if (userData.studentId.length > 20) {
                Message.error('学号长度不能超过20个字符')
                return
              }
              
              console.log('创建用户数据:', userData) // 添加日志
              console.log('提交到后端的头像URL长度:', userData.avatar.length) // 添加提交给后端的头像URL长度日志
              
              try {
                response = await userService.createUser(userData)
                console.log('创建用户响应:', response) // 添加响应日志
              } catch (error) {
                console.error('创建用户请求失败:', error)
                console.error('请求数据:', userData)
                if (error.response) {
                  console.error('响应状态:', error.response.status)
                  console.error('响应数据:', error.response.data)
                  console.error('错误详情:', JSON.stringify(error.response.data, null, 2))
                  throw new Error(error.response.data.message || '创建用户失败')
                }
                throw error
              }
            } else {
              // 编辑模式下分别更新各个字段
              const currentUser = this.userList.find(u => u.userId === this.currentId)
              if (currentUser) {
                const updatePromises = []
                
                if (this.form.nickname !== currentUser.nickname) {
                  updatePromises.push(userService.updateNickname(this.currentId, this.form.nickname.trim()))
                }
                if (this.form.phone !== currentUser.phone) {
                  updatePromises.push(userService.updatePhone(this.currentId, this.form.phone.trim()))
                }
                // 编辑时头像处理：直接发送用户选择的完整头像URL，因为现在URL是短的，可以完整存储
                if (this.form.avatar !== currentUser.avatar) {
                  updatePromises.push(userService.updateAvatar(this.currentId, this.form.avatar))
                }
                
                // 等待所有更新完成
                await Promise.all(updatePromises)
                response = { code: 200, message: '更新成功' }
              }
            }

            if (response && response.code === 200) {
              Message.success(this.dialogType === 'add' ? '添加成功' : '更新成功')
              this.dialogVisible = false
              
              // 根据操作类型，本地更新用户列表，而不是重新获取所有用户
              if (this.dialogType === 'add') {
                const newUser = {
                  userId: response.data?.userId, // 假设后端返回新用户的ID
                  studentId: this.form.studentId.trim(),
                  nickname: this.form.nickname.trim(),
                  phone: this.form.phone.trim(),
                  avatar: this.form.avatar, // 使用用户选择的完整头像URL
                  // 如果后端返回了创建时间，则使用，否则使用当前时间
                  createTime: response.data?.createTime || new Date().toISOString()
                };
                this.userList.push(newUser);
              } else {
                const index = this.userList.findIndex(u => u.userId === this.currentId);
                if (index !== -1) {
                  // 使用Vue的响应式更新方法
                  this.$set(this.userList, index, {
                    ...this.userList[index],
                    nickname: this.form.nickname.trim(),
                    phone: this.form.phone.trim(),
                    avatar: this.form.avatar // 使用用户选择的完整头像URL
                  });
                }
              }
              this.updateTotal(); // 更新分页的总数和重新计算分页列表

            } else {
              console.error('响应异常:', response)
              Message.error(response?.message || (this.dialogType === 'add' ? '添加失败' : '更新失败'))
            }
          } catch (error) {
            console.error(this.dialogType === 'add' ? '添加用户失败:' : '更新用户失败:', error)
            console.error('错误堆栈:', error.stack)
            if (error.response?.data?.message) {
              console.error('错误详情:', JSON.stringify(error.response.data, null, 2))
              Message.error(error.response.data.message)
            } else {
              console.error('错误对象:', error)
              Message.error(error?.message || (this.dialogType === 'add' ? '添加用户失败' : '更新用户失败'))
            }
          }
        }
      })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.updateTotal()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
    },

    // 返回上一页或首页
    goBack() {
      if (this.$route.query.from === 'dashboard') {
        this.$router.push('/dashboard')
      } else {
        this.$router.go(-1)
      }
    },

    // 刷新用户数据
    async refreshUsers() {
      await this.fetchUsers()
    },
  }
}
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  .stats-content {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .stats-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #409EFF;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;

    &.active {
      background-color: #67C23A;
    }

    &.new {
      background-color: #E6A23C;
    }
  }

  .stats-info {
    .stats-number {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 5px;
    }

    .stats-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-selector {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  padding: 10px 0;
}

.avatar-option {
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 50%;
  padding: 2px;
  transition: all 0.3s ease;
}

.avatar-option:hover {
  transform: scale(1.05);
}

.avatar-option.selected {
  border-color: #409EFF;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}
</style> 